package com.yuven.baselib.utils;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 管理线程池的工具类 可以调用{@link #execute(Runnable)}
 * 
 * @author andyzhang
 * */
public class ThreadUtils
{
    /**
     * the factory object used to create threads for thread pool
     * 
     * @author ytchu
     */
    private static final class DefaultThreadFactory implements ThreadFactory
    {
        private static final String PREFIX = "sdk-pooled-thread-";
        
        private static final AtomicInteger COUNTER = new AtomicInteger();
        
        @Override
        public Thread newThread(Runnable task)
        {
            Thread t = new Thread(Thread.currentThread().getThreadGroup(),
                    task, PREFIX + COUNTER.getAndIncrement());
            
            // set the uncaught exception handler to log the global exception caught by the JVM
            t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
            {
                @Override
                public void uncaughtException(Thread thread, Throwable ex)
                {
                    Logger.i(TAG,
                            "Exception occurred at the thread [".concat(thread.getName())
                                    .concat("],detail message is:\r\n")
                                    .concat(ex.getMessage()));
                }
            });
            return t;
        }
    }
    
    private static final String TAG = "ThreadUtils";
    
    /** 创建线程池 */
    private static ExecutorService executor = null;
    
    /**
     * 执行Runnable形式的任务
     * 
     * @param task
     *            需要执行的任务
     * */
    public static void execute(Runnable task)
    {
        prepare();
        executor.execute(task);
    }
    

    public static synchronized void prepare()
    {
        if (executor == null || executor.isShutdown())
        {
            executor = null;
            executor = Executors.newCachedThreadPool(new DefaultThreadFactory());
        }
    }

}
